from datastore.resource import *
from datastore.uri import *
from runtime.service import *

# testing
import hashlib

class IndexService(Service):
    def cb_start(self, uri, action, res):
        self.spaces.set_watch(res.options.watch, self.cb_index)

    def cb_index(self, uri, action, res):
        # res = 'term:base/services/index/entry'
        if action in ['put', 'update']:
            # res.index e.g. 'external:examples/'
            # res.uri   e.g. 'external:examples/hello-world'
            # dc_title = text
            # dc_description = tooltip
            
            # or should we just index anything in the collection?
            # the problem is that we don't get to specify the metadata?
            
            # term:base/services/index/page
            
            # check if the page already exists
            index = self.spaces.get(res.index)
            title = res.dc_title(default='unknown')
            description = res.dc_description(default='')
            if index is None:
                index = Resource(type='term:base/services/index/page')
                index.dc_title('Index')
                index.index = {res.uri: {'title': title,
                                         'description': description}}
            else:
                index.index[res.uri] = {'title': title,
                                        'description': description}
            self.spaces.put(res.index, index)
